package com.shitou.shitoumember.listener;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rabbitmq.client.Channel;
import com.shitou.shitoucommons.exception.RRException;
import com.shitou.shitoucommons.utils.MemberLevelCountUtils;
import com.shitou.shitoucommons.utils.RespBean;
import com.shitou.shitoucommons.vo.ConnectionVo;
import com.shitou.shitoucommons.vo.FeignProductVo;
import com.shitou.shitoucommons.vo.MemberVo;
import com.shitou.shitoumember.config.MessagingRoom;
import com.shitou.shitoumember.config.RabbitMQConfig;
import com.shitou.shitoumember.entity.GrowthChangeHistoryEntity;
import com.shitou.shitoumember.entity.MemberEntity;
import com.shitou.shitoumember.entity.MemberLevelEntity;
import com.shitou.shitoumember.entity.MemberStatisticsInfoEntity;
import com.shitou.shitoumember.feign.SpuFeign;
import com.shitou.shitoumember.service.*;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;

/**
 * class detail:
 *      rabbitmq监听，监听用户行为
 * @author 石头人
 */
@SuppressWarnings("all")
@Component
@Transactional
public class MemberListener {

    @Autowired
    private MemberService umsMemberService;
    @Autowired
    private GrowthChangeHistoryService growthChangeHistoryService;
    @Autowired
    private MemberLevelService memberLevelService;
    @Autowired
    private MemberStatisticsInfoService statisticsInfoService;
    @Autowired
    private SpuFeign spuFeign;
    @Autowired
    private SendReceiveService sendReceiveService;
    @Autowired
    private MessagingRoom messagingRoom;


    @RabbitListener(queues = {RabbitMQConfig.MEMBER_OPTION_QUEUE})
    public void optionListen(String msg, Channel channel, Message message){
        try {
            MemberVo memberVo = JSON.parseObject(msg, MemberVo.class);
            // 修改买家用户的信息
            memberDo(memberVo.getMemberId(), memberVo.getGrowth(),
                    Double.valueOf(memberVo.getPayAmount().toString()), 0, null);

            // 计算卖家的赚取金额，修改信息
            long[] spuIds = memberVo.getSpuIds();
            RespBean respBean = spuFeign.getMemberIds(spuIds);
            if ( respBean == null ){
                throw new RRException("获取卖家信息为空");
            }
            FeignProductVo feignProductVo  = JSON.parseObject((String) respBean.get("data"), FeignProductVo.class);
            System.out.println(feignProductVo);
            long[] memberIds = feignProductVo.getMemberIds();
            BigDecimal[] prices = feignProductVo.getPrices();
            String[] spuNames = feignProductVo.getNames();

            for (int i = 0 ; i < spuIds.length ; i++ ) {
                // 修改卖家用户的信息
                memberDo(memberIds[i], 50, 0, Double.valueOf(prices[i].toString()),spuNames[i]);
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new RRException(e.getMessage());
        } finally {
            try {
                System.out.println("手动签收");
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }


    /**
     *
     * @param memberId 会员id
     * @param growth   改变的成长值
     * @param payAmount   支付的金额
     * @param earnAmount   赚取的金额
     * @param productName  商品的名称
     */
    public void memberDo(long memberId, Integer growth, double payAmount, double earnAmount, String productName){

        MemberEntity member = umsMemberService.getOne(new QueryWrapper<MemberEntity>().eq("id", memberId));
        Date date = new Date();

        // 增加成长值信息
        GrowthChangeHistoryEntity growthChangeHistory = new GrowthChangeHistoryEntity();
        growthChangeHistory.setMemberId(member.getId());
        growthChangeHistory.setChangeCount(growth);
        growthChangeHistory.setCreateTime(date);
        if ( productName == null || productName.equals("") ){
            growthChangeHistory.setNote("您购物了，获得了成长值");
        }else {
            growthChangeHistory.setNote("您售卖了商品: " + productName + " 获得了成长值");
        }
        growthChangeHistory.setSourceType(0);  // 积分来源于购物
        growthChangeHistoryService.save(growthChangeHistory);

        // 更新用户level表，等级信息表
        MemberLevelEntity memberLevel = memberLevelService.getOne(new QueryWrapper<MemberLevelEntity>().eq("id", member.getLevelId()));
        memberLevel.setGrowthPoint(growthChangeHistory.getChangeCount() + memberLevel.getGrowthPoint());  // 更新成长值
        String levelName = MemberLevelCountUtils.lvelCount(memberLevel.getGrowthPoint());
        System.out.println("当前等级: " + levelName);
        memberLevel.setName(levelName);    // 计算等级
        String levelNote = MemberLevelCountUtils.levelNote(memberLevel.getGrowthPoint());
        System.out.println("当前等级描述: " + levelNote);
        memberLevel.setNote(levelNote);    // 每个等级的对于描述
        Integer commentGrowtnPoint = MemberLevelCountUtils.commentGrowthPoint(memberLevel.getGrowthPoint());
        System.out.println("该等级评论一次的成长值: " + commentGrowtnPoint);
        memberLevel.setCommentGrowthPoint(commentGrowtnPoint);   // 该等级对应的评论获取成长值
        memberLevel.setPriviledgeFreeFreight(MemberLevelCountUtils.freeFreight(memberLevel.getGrowthPoint()));  // 是否免邮
        memberLevelService.updateById(memberLevel);

        // 买家用户会员数据统计表
        MemberStatisticsInfoEntity statisticsInfo = statisticsInfoService.getOne(
                new QueryWrapper<MemberStatisticsInfoEntity>().eq("member_id", member.getId()));
        statisticsInfo.setOrderCount( statisticsInfo.getOrderCount() + 1);   // 订单数+1
        statisticsInfo.setConsumeAmount((statisticsInfo.getConsumeAmount().add(BigDecimal.valueOf(payAmount))));   // 会员累计消费金额
        statisticsInfo.setEarnAmount(statisticsInfo.getEarnAmount().add(BigDecimal.valueOf(earnAmount)));   // 会员赚取金额
        // TODO 用户售卖订单，数据字段未添加

        statisticsInfoService.updateById(statisticsInfo);
    }


    /**
     * 发送站内信队列s
     * @param messageVo
     * @param channel
     * @param message
     */
    @RabbitListener(queues = {RabbitMQConfig.SEND_MESSAGAING_QUEUE})
    public void sendMessaging(String messageVo, Channel channel, Message message) throws IOException {
        messagingRoom.onMessage(messageVo);
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }


    /**
     * 购买者和发布者之间进行联系链接
     * @param msg
     * @param channel
     * @param message
     * @throws IOException
     */
    @RabbitListener(queues = {RabbitMQConfig.CONNECTION_MEMBER_QUEUE})
    public void connectionMember(String msg, Channel channel, Message message) throws IOException {
        ConnectionVo connectionVo = JSON.parseObject(msg, ConnectionVo.class);
        sendReceiveService.createSendReceive(connectionVo.getMembreId(), connectionVo.getReceiveMemberId());
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
}
